import { getCurrentInstance, onUnmounted } from 'vue'

const observerCache = {}
/**
 * 用于支持观察者模式的hooks
 */
export function useObserver() {
  const instance = getCurrentInstance();

  if (!observerCache[instance.uid]) {
    observerCache[instance.uid] = new Observer()
  }

  onUnmounted(() => {
    delete observerCache[instance.uid]
  })

  return observerCache[instance.uid] as IObserver;
}



export class Observer {
  private observers: IObserverItem[] = []

  public add(type: string, func: (...args) => void, rank: number) {
    this.observers.push({ func, rank, type })
  }

  public trigger(type: string, ...args) {
    this.observers.filter(s => s.type === type).forEach(item => {
      item.func.call(null, ...args)
    })
  }
}

